//
//  MYGCloudDiskAddFileSheet.swift
//  MYDoctor
//
//  Created by Denny on 2024/3/11.
//

import UIKit
import TZImagePickerController
class MYGCloudDiskAddFileSheet: UIView {
    @IBOutlet weak var leftMargin2: NSLayoutConstraint!
    @IBOutlet weak var leftMarign5: NSLayoutConstraint!
    @IBOutlet weak var leftMargin6: NSLayoutConstraint!
    @IBOutlet weak var leftMargin4: NSLayoutConstraint!
    @IBOutlet weak var leftMargin3: NSLayoutConstraint!
    @IBOutlet weak var leftMargin1: NSLayoutConstraint!
    var hideShare : Bool = false {
        didSet {
            self.shareBtn.isHidden = hideShare
        }
    }
    var tapCloseCompletion:(()->Void)?
    var tapShareCompletion:(()->Void)?
    var tapCreatFileCompletion:(()->Void)?
    var fid = 0 //0最外层，大于0某个文件夹下
    @IBOutlet weak var shareBtn: UIButton!
    override func awakeFromNib() {
        super.awakeFromNib()
        let margin = max(0, (screenWidth - 60 * 4)/5)
        leftMargin1.constant = margin
        leftMargin2.constant = margin
        leftMargin3.constant = margin
        leftMargin4.constant = margin
        leftMarign5.constant = margin
        leftMargin6.constant = margin
    }
    
    @IBAction func closeAlert(_ sender: UIButton) {
        dismissSelf()
    }
    
    func dismissSelf() {
        if let con = tapCloseCompletion {
            con()
        }
    }
    //本地文件
    @IBAction func tapLocalFile(_ sender: UIButton) {
        presentDocumentCloud()
    }
    //本地图片
    @IBAction func tapLocalPic(_ sender: UIButton) {
        guard let picker = TZImagePickerController.init(maxImagesCount: 9, columnNumber: 4, delegate: self, pushPhotoPickerVc: false) else {return}
        picker.modalPresentationStyle = .fullScreen
        picker.allowTakeVideo = false
        picker.allowPickingVideo = false
        picker.allowPickingImage = true
        self.rootResponsder().present(picker, animated: true)
    }
    //本地视频
    @IBAction func tapLocalVideo(_ sender: UIButton) {
        guard let picker = TZImagePickerController.init(maxImagesCount: 9, columnNumber: 4, delegate: self, pushPhotoPickerVc: false) else {return}
        picker.modalPresentationStyle = .fullScreen
        picker.allowPickingVideo = true
        picker.allowPickingImage = false
        self.rootResponsder().present(picker, animated: true)
    }
    //相机
    @IBAction func tapLocalTakePic(_ sender: UIButton) {
        let picker = UIImagePickerController()
        picker.sourceType = .camera
        picker.allowsEditing = true
        picker.delegate = self
        self.rootResponsder().present(picker, animated: true)
    }
    //新建文件夹
    @IBAction func tapCreatFile(_ sender: UIButton) {
        if let c = tapCreatFileCompletion {
            c()
        }
    }
    //分享
    @IBAction func tapShare(_ sender: UIButton) {
        if let com = tapShareCompletion {
            com()
        }
    }
    
    func presentDocumentCloud() {
        let documentTypes = [
            "public.content",
            "public.source-code",
            "public.image",
            "public.audiovisual-content",
            "com.adobe.pdf",
            "com.apple.keynote.key",
            "com.microsoft.word.doc",
            "com.microsoft.excel.xls",
            "com.microsoft.powerpoint.ppt"
        ]
        
        let documentPickerViewController = UIDocumentPickerViewController(documentTypes: documentTypes, in: .import)
        documentPickerViewController.delegate = self
        self.rootResponsder().present(documentPickerViewController, animated: true, completion: nil)
    }
}

//照片、视频
extension MYGCloudDiskAddFileSheet: TZImagePickerControllerDelegate {
    //视频
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: PHAsset!) {
        TZImageManager().requestVideoURL(with: asset) { url in
            guard let url = url, let data = try? Data(contentsOf: url) else {return}
            MYGUploadManager.shared.addUploadTask(fileData: data, fileName: "\(Int(Date().timeIntervalSince1970)).mp4", type: .video, fid: self.fid)
        } failure: { params in
            print("视频获取失败")
        }
       
        DispatchQueue.main.async(execute: {
            picker.dismiss(animated: true, completion: nil)
        })
    }
    
    //照片
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        guard let pics = photos.first else {
            return
        }
        guard let imageData = pics.jpegData(compressionQuality: 0.1) else {return}
        MYGUploadManager.shared.addUploadTask(fileData: imageData, fileName: "\(Int(Date().timeIntervalSince1970)).png", type: .image, fid: self.fid)

        DispatchQueue.main.async(execute: {
            picker.dismiss(animated: true, completion: nil)
        })
    }
}

//系统文件
extension MYGCloudDiskAddFileSheet : UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        let components = url.absoluteString.components(separatedBy: "/")
        if let name = components.last,let  fileName = name.removingPercentEncoding {
            ICouldManager.downloadFile(WithDocumentUrl: url) { (fileData) in
                if fileData.isEmpty {return}
                MYGUploadManager.shared.addUploadTask(fileData: fileData, fileName: fileName, type: .file, fid: self.fid)
            }
        }
    }
}
//拍照
extension MYGCloudDiskAddFileSheet :UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else{
            return
        }
        guard let imageData = image.jpegData(compressionQuality: 0.1) else {return}
        MYGUploadManager.shared.addUploadTask(fileData: imageData, fileName: "\(Int(Date().timeIntervalSince1970)).png", type: .image, fid: self.fid)
    }
}

